<?php
class User{
	public function Login($username,$password){
		$password = sha1($password);
		$sql = "select * from user where username = '$username' and password = '$password'";
		$DB = new DB();
		$row=$DB->fetchRow($sql);
		if($row){
			$_SESSION['userid'] = $row['id'];
			$_SESSION['type'] = $row['type'];
		}
		return $row;
		
	}
	 public function add($username,$password,$realname,$contact,$type='')
	 {
		$DB = new DB();
		$password = sha1($password);
		$sql = "select * from user where username ='$username'";
		$check_user = $DB->fetchAll($sql);
		
		if($check_user)
		{
			echo "used";
			return false;
		}
		
		$sql = "INSERT INTO `user` VALUES (:id,:username,:password,:type,:contact,:realname)";
		$field = array(':id' => '',
					   ':username' => $username,
					   ':password' => $password,
					   ':type' => $type,
					   ':contact' => $contact,
					   ':realname' => $realname
					  );

		return $DB->updateDB($sql,$field);			   
	 }	
	 
	public function edit($id,$name,$password='',$realname,$contact){
		
		$sql = "UPDATE user set username=?,realname=?,contact=?";
		if($password){
			$password = sha1($password);
			$sql.=",password=?";
			$field = array($name,$realname,$contact,$password);
		}
		else{
			$field = array($name,$realname,$contact);
		}
		$sql.="where id='$id'";
		
		
		return DB::updateDB($sql,$field);
	}
	 
	 public function del($id){
		global $db;
		$sql = "delete from user where id='$id'";
		return $db->query($sql);	 
	 }
	 
	public function getUser($field,$value){
		$DB = new DB();
		$sql = "select * from user where $field ='$value'";
		return $DB->fetchAll($sql);
	}	 
	
	public function getStat($title,$status=''){
		$DB = new DB();
		$sql = "select count(*) as total from `$title`";
		if($status){
			$sql.=" where type='$status'";
		}
		return $DB->count($sql);
		
		
	}
	
	public function getTeacher($id){
		$sql = "SELECT
				u.*,c.id as class,g.id as grade
			    FROM
				class c,user u,grade g
				WHERE
				u.id = '$id'
				AND 
				u.id = c.teacher_id
				AND
				c.grade_id = g.id";
		return DB::fetchRow($sql);			
	}	
	
	public function getLastId(){
		$sql = "SELECT
				max(id) AS id 
				FROM
				user";
		return DB::fetchRow($sql);	
	}
}
?>